# coding = utf-8
import os

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
#from PIL import Image
# from mahotas.features import surf
import tkinter as tk
import pymysql  #pip install PyMySQL
from tkinter import filedialog

root = tk.Tk()
root.geometry("500x500")
root.title("ORB特征点")

image = None

mask_out = None


def mask_mask_padding():
    paddingTop = 650
    paddingButtom = 100
    padding_v = padding_e.get()
    padding_arr = padding_v.split(",")
    if padding_arr[0] == '':
        padding_arr = []
    if len(padding_arr) == 1:
        paddingTop = int(padding_arr[0])
    elif len(padding_arr) == 2:
        paddingTop = int(padding_arr[0])
        paddingButtom = int(padding_arr[1])
    maskAll = np.zeros(image.shape[0:2], dtype="uint8")
    cv.rectangle(maskAll, (0, paddingTop), (image.shape[1], image.shape[0] - paddingButtom), 255, -1)
    # cv.rectangle(maskTop,(0,1400),(image_copy.shape[1],image_copy.shape[0]),255,-1)
    # #cv.rectangle(maskTop,(0,0),(image_copy.shape[1],1400),255,-1)
    # # gray = cv.blur(gray,(3,3))
    # # #ret, maskBW = cv.threshold(gray, 50, 100, cv.THRESH_BINARY)
    # # ret, maskBW = cv.threshold(gray, 180, 255, cv.THRESH_BINARY)   #白色范围
    # # maskAll = cv.bitwise_and(maskTop,maskBW)
    # 提取关注颜色
    # # hsv = cv.cvtColor(image_copy,cv.COLOR_BGR2HSV)
    # # mask_color = cv.inRange(hsv,np.array([0,0,0]),np.array([180,255,46]))
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
    global mask_out
    mask_out = cv.bitwise_and(gray, maskAll)
    cv.imwrite('out/orb_mask_out.jpg', mask_out)
    return maskAll


def choose_image():
    src_FILE = filedialog.askopenfilename(initialdir="images/", title="选择图片",
                                          filetypes=(("JPEG files", "*.jpg"), ("PNG files", "*.png")))
    input_path.set(src_FILE)
    # 导入资源
    global image
    image = cv.imread(src_FILE)  # r"D:\data\IMG_20230719_105059.jpg"
    # image_show = cv.imdecode(np.fromfile(src_FILE, dtype=np.uint8), -1)
    # image_copy = np.copy(image_show)
    image_copy = cv.cvtColor(image, cv.COLOR_BGR2RGB)
    plt.imshow(image_copy)
    plt.show()  #最终显示


def do_image():
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)

    # 检测角点
    # orb = cv.ORB_create(500, 1.2,scoreType=1,fastThreshold=20*2)
    orb = cv.ORB_create(scaleFactor=pow(2,0.5))  # 500,scoreType=0,1, patchSize=31*4
    maskAll = mask_mask_padding()
    keypoints, desc = orb.detectAndCompute(gray, maskAll)  # maskTop
    print("Num of keypoints: ", len(keypoints))
    print("Shape of kp desscriptors:", desc.shape)

    # 绘制角点,转变为彩色
    corner_image = cv.cvtColor(mask_out, cv.COLOR_GRAY2RGB)  # np.copy(image_copy)

    # def draw_keypoints(img, keypoints, color = (0, 255, 0)):
    #     for kp in keypoints:
    #         x, y = kp.pt
    #         cv.circle(img, (int(x), int(y)), 10, color,2)
    #
    # draw_keypoints(corner_image, keypoints)

    # imgS = cv.convertScaleAbs(corner_image,alpha=0.5,beta=128)
    keypoints_list = list(keypoints)
    keypoints_list.sort(key=lambda x:x.size,reverse=True)
    keypoints_new = tuple(keypoints_list)
    imgKp2 = cv.drawKeypoints(corner_image, keypoints_new[:100], None, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    # 关键点信息查看
    # print(keypoint)  # [<KeyPoint 000001872E1E2960>, <KeyPoint 000001872E1E2B10>]
    # original_kp_set = {(int(kp.pt[0]), int(kp.pt[1])) for kp in keypoints}  # pt查看关键点坐标
    # print(original_kp_set)
    # cv.drawKeypoints(corner_image,keypoints,corner_image,flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

    # for point in keypoints:
    #     cv.circle(corner_image, (int(point.pt[0]), int(point.pt[1])), 10, (0,255,0), 2)

    # cv.imwrite('ORB.jpg', corner_image)
    out_file_path = 'out/ORB.jpg'
    cv.imwrite(out_file_path, imgKp2)
    out_file_path_full = os.path.join(os.getcwd(),out_file_path)
    print(out_file_path_full)
    out_e.set(out_file_path_full)
    os.startfile(out_file_path_full)

def do_image2():
    #创建连接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',password="toor" , db='img_point',charset = 'utf8')
    sql = "insert into img_info(path,size) values (%s, %s)"
    cursor = conn.cursor()
    cursor.execute(sql,(input_path.get(),os.path.getsize(input_path.get()))) #
    lastId = cursor.lastrowid
    print(lastId)
    #特征点处理
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)

    # 检测角点
    # orb = cv.ORB_create(500, 1.2,scoreType=1,fastThreshold=20*2)
    orb = cv.ORB_create(scaleFactor=pow(2,0.5))  # 500,scoreType=0,1, patchSize=31*4
    maskAll = mask_mask_padding()
    keypoints, desc = orb.detectAndCompute(gray, maskAll)  # maskTop
    print("Num of keypoints: ", len(keypoints))
    print("Shape of kp desscriptors:", desc.shape)

    point_list = []
    for point in keypoints:
        #print(point)
        pixel_color = image[int(point.pt[1]),int(point.pt[0])]
        row = (lastId,point.pt[0],point.pt[1],point.size,point.angle,point.response,point.octave,pixel_color)
        point_list.append(row)

    sql = "insert into img_point(img_info_id,pt_x,pt_y,size,angle,response,octave,color) values (%s, %s,%s, %s,%s, %s,%s, %s)"
    cursor.executemany(sql,point_list)
    conn.commit()
    cursor.close()
    print("导入成功")
    out_e.set("导入成功")

button = tk.Button(root, text="选择图片", command=choose_image)
button.pack(side="top", pady=20)

input_path = tk.StringVar()
input_label = tk.Label(root, text='图片:', textvariable=input_path)
input_label.pack(side="top")

padding_label = tk.Label(root, text='padding')  # ,anchor='c').grid(row=0,column=0)
padding_label.pack(side="top")
padding_e = tk.StringVar()
padding = tk.Entry(root, width=20, textvariable=padding_e)  # .grid(row=0,column=1)
padding.pack(side="top")
# padding_e.set('输入padding参数，,分隔上下边距的像素')

button_do = tk.Button(root, text="检测特征点", command=do_image)
button_do.pack(side="top", pady=50)

button_do2 = tk.Button(root, text="特征点导入数据库", command=do_image2)
button_do2.pack(side="top", pady=50)

out_e = tk.StringVar()
out_label = tk.Label(root, text='输处目录:', textvariable=out_e)
out_label.pack(side="bottom")

root.mainloop()
